package com.newthread.android.ui.bbs;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.Toast;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.jpush.im.android.eventbus.EventBus;

import com.actionbarsherlock.app.SherlockFragment;
import com.bmob.BmobProFile;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView;
import com.matthewlogan.circlemenu.library.CircleMenu;
import com.newthread.android.R;
import com.newthread.android.activity.main.MyApplication;
import com.newthread.android.adapter.BbsGroupEpListAdapter;
import com.newthread.android.bean.StudentUserLocal;
import com.newthread.android.bean.remoteBean.StudentUser;
import com.newthread.android.util.Loger;

import net.tsz.afinal.FinalDb;

import java.util.*;

/**
 * Created by jindongping on 15/6/4.
 */
public class BbsGroupFrament extends SherlockFragment {
    private LayoutInflater inflater;
    private ExpandableListView expandableListView;
    private PullToRefreshExpandableListView pullToRefreshExpandableListView;
    private Context context;
    private BbsGroupEpListAdapter adapter;
    private String[] generalsTypes = new String[]{""};
    private List<List<StudentUserLocal>> generals;
    private CircleMenu mCircleMenu;
    private List<StudentUserLocal> users = null;

    public enum STATES {展开分组菜单, 性别, 班级, 宿舍, 专业, 年级, 省份, 民族, 家庭住址;}

    private static String[] circleMenuItems = new String[]{"性别", "班级", "宿舍", "专业", "年级", "省份", "民族", "家庭住址"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity().getApplicationContext();
        EventBus.getDefault().register(this);
    }


    /**
     * 如果注册 EventBus 就必须有onEventXXX(有参数)方法
     * 接收分组事件
     *
     * @param message 分组类型：如 省份 民族 专业 年级 班级 家庭住址 宿舍 性别
     *                还可以展开分组菜单:展开分组菜单
     */
    public void onEventMainThread(STATES message) {
        if (message == STATES.展开分组菜单) {
            mCircleMenu.toggle();
            return;
        }
        noticeDataChange(message.name());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.inflater = inflater;
        View viewRoot = inflater.inflate(R.layout.fragment_bbs_group, container, false);
        initView(viewRoot);
        initData();
        return viewRoot;
    }

    private void initView(View viewRoot) {
        pullToRefreshExpandableListView = (PullToRefreshExpandableListView) viewRoot.findViewById(R.id.expandableListView);
        mCircleMenu = (CircleMenu) viewRoot.findViewById(R.id.circle_menu);
        mCircleMenu.setItems(circleMenuItems);
        mCircleMenu.setOnItemClickListener(new CircleMenu.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                mCircleMenu.toggle();
                switch (position) {
                    case 0:
                        EventBus.getDefault().post(STATES.性别);
                        break;
                    case 1:
                        EventBus.getDefault().post(STATES.班级);
                        break;
                    case 2:
                        EventBus.getDefault().post(STATES.宿舍);
                        break;
                    case 3:
                        EventBus.getDefault().post(STATES.专业);
                        break;
                    case 4:
                        EventBus.getDefault().post(STATES.年级);
                        break;
                    case 5:
                        EventBus.getDefault().post(STATES.省份);
                        break;
                    case 6:
                        EventBus.getDefault().post(STATES.民族);
                        break;
                    case 7:
                        EventBus.getDefault().post(STATES.家庭住址);
                        break;
                    default:
                        EventBus.getDefault().post(STATES.专业);
                        break;
                }
            }
        });
        expandableListView = pullToRefreshExpandableListView.getRefreshableView();
        //设置item点击的监听器
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                MyApplication.getInstance().putThing("clickUser", generals.get(groupPosition).get(childPosition));
                Intent intent = new Intent(context, BbsChatActivity.class);
                startActivity(intent);
                return false;
            }
        });
        pullToRefreshExpandableListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ExpandableListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ExpandableListView> refreshView) {
                QuerryAllStuUser(FinalDb.create(context, "onMinDaBbs"), refreshView);
            }
        });

    }


    /**
     * 从网络查询所有用户 然后赋值给users 保存到数据库
     *
     * @param db
     */
    private void QuerryAllStuUser(final FinalDb db, final PullToRefreshBase refreshBase) {
        //查询所有用户
        BmobQuery<StudentUser> query = new BmobQuery<>();
        query.findObjects(context, new FindListener<StudentUser>() {
            @Override
            public void onSuccess(List<StudentUser> list) {
                //解密头像地址
                for (StudentUser user : list) {
                    String image = BmobProFile.getInstance(context).signURL(user.getHeadPhotoName(),
                            user.getHeadPhotoUrl(), "430a4eb2231a964487b2fa2c42cff1bb", 0, null);
                    user.setHeadRealPhotoUrl(image);
                }
                //不将密码保存到本地,虽然可以用 @Transient不保存字段，但是为了避免StudentUser过度复杂，从而引入StudentUserLocal
                users = ChangeToLocalUser(list);
                if (refreshBase != null) {
                    refreshBase.onRefreshComplete();
                    Toast.makeText(context, "查询数据成功", Toast.LENGTH_LONG).show();
                    db.deleteAll(StudentUserLocal.class);
                }
                for (StudentUserLocal user : users) {
                    db.save(user);
                }
                noticeDataChange(STATES.专业.name());
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(context, "查询失败,请检查网络", Toast.LENGTH_LONG).show();
                if (refreshBase != null)
                    refreshBase.onRefreshComplete();
            }
        });
    }

    private void initData() {
        final FinalDb db = FinalDb.create(context, "onMinDaBbs");
        //从数据库查用户数据 没有就从网络上查并保存到数据库
        List<StudentUserLocal> users_db = db.findAll(StudentUserLocal.class);
        if (users_db == null || users_db.size() < 1) {
            QuerryAllStuUser(db, null);
        } else {
            users = users_db;
            noticeDataChange("专业");
        }
    }

    private List<StudentUserLocal> ChangeToLocalUser(List<StudentUser> users) {
        List<StudentUserLocal> localUsers = new ArrayList<>();
        for (StudentUser user : users) {
            localUsers.add(new StudentUserLocal(user.getObjectId(), user.getUsername(), user.getName(), user.getSex(), user.getAge(),
                    user.getQq(), user.getWeiXin(), user.getMobPhone(), user.getBrithDay(), user.getProvince()
                    , user.getPoliticsStatus(), user.getNation(), user.getDepartMent(),
                    user.getMarjar(), user.getNianji(), user.getClassNumber(),
                    user.getFrom(), user.getLiveAddress(), user.getHeadRealPhotoUrl()));
        }
        return localUsers;
    }

    /**
     * @param groupType 分组类型：如 省份 民族 专业 年级 班级 家庭住址 宿舍 性别
     */
    private void noticeDataChange(String groupType) {
        //转换分解成适配器能接受的数据
        changeData(users, groupType);
        adapter = new BbsGroupEpListAdapter(generalsTypes, generals, inflater);
        expandableListView.setAdapter(adapter);
    }

    /**
     * @param users     需要转换的userLocal对象
     * @param groupType 分组类型：如 省份 民族 专业 年级 班级 家庭住址 宿舍 性别
     */
    private void changeData(List<StudentUserLocal> users, String groupType) {
        Map<String, List<StudentUserLocal>> map = new HashMap<>();
        for (int i = 0; i < users.size(); i++) {
            String key;
            List<StudentUserLocal> value;
            switch (groupType) {
                case "省份":
                    key = users.get(i).getProvince();
                    if (key == null || key.equals("")) {
                        key = "未知";
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = 0; j < users.size(); j++) {
                            String strTemp = users.get(j).getProvince();
                            if ((strTemp == null || strTemp.equals("")) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                            map.put(key, value);
                        }
                    } else {
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = i; j < users.size(); j++) {
                            if (key.equals(users.get(j).getProvince()) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                        }
                        map.put(key, value);
                    }
                    break;
                case "民族":
                    key = users.get(i).getNation();
                    if (key == null || key.equals("")) {
                        key = "未知";
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = 0; j < users.size(); j++) {
                            String strTemp = users.get(j).getNation();
                            if ((strTemp == null || strTemp.equals("")) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                            map.put(key, value);
                        }
                    } else {
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = i; j < users.size(); j++) {
                            if (key.equals(users.get(j).getNation()) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                        }
                        map.put(key, value);
                    }
                    break;
                case "专业":
                    key = users.get(i).getMarjar();
                    if (key == null || key.equals("")) {
                        key = "未知";
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = 0; j < users.size(); j++) {
                            String strTemp = users.get(j).getMarjar();
                            if ((strTemp == null || strTemp.equals("")) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                            map.put(key, value);
                        }
                    } else {
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = i; j < users.size(); j++) {
                            if (key.equals(users.get(j).getMarjar()) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                        }
                        map.put(key, value);
                    }
                    break;
                case "年级":
                    key = users.get(i).getNianji();
                    if (key == null || key.equals("")) {
                        key = "未知";
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = 0; j < users.size(); j++) {
                            String strTemp = users.get(j).getNianji();
                            if ((strTemp == null || strTemp.equals("")) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                            map.put(key, value);
                        }
                    } else {
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = i; j < users.size(); j++) {
                            if (key.equals(users.get(j).getNianji()) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                        }
                        map.put(key, value);
                    }
                    break;
                case "班级":
                    key = users.get(i).getClassNumber();
                    if (key == null || key.equals("")) {
                        key = "未知";
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = 0; j < users.size(); j++) {
                            String strTemp = users.get(j).getClassNumber();
                            if ((strTemp == null || strTemp.equals("")) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                            map.put(key, value);
                        }
                    } else {
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = i; j < users.size(); j++) {
                            if (key.equals(users.get(j).getClassNumber()) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                        }
                        map.put(key, value);
                    }
                    break;
                case "家庭住址":
                    key = users.get(i).getWhereForm();
                    if (key == null || key.equals("")) {
                        key = "未知";
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = 0; j < users.size(); j++) {
                            String strTemp = users.get(j).getWhereForm();
                            if ((strTemp == null || strTemp.equals("")) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                            map.put(key, value);
                        }
                    } else {
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = i; j < users.size(); j++) {
                            if (key.equals(users.get(j).getWhereForm()) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                        }
                        map.put(key, value);
                    }
                    break;
                case "宿舍":
                    key = users.get(i).getLiveAddress();
                    if (key == null || key.equals("")) {
                        key = "未知";
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = 0; j < users.size(); j++) {
                            String strTemp = users.get(j).getLiveAddress();
                            if ((strTemp == null || strTemp.equals("")) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                            map.put(key, value);
                        }
                    } else {
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = i; j < users.size(); j++) {
                            if (key.equals(users.get(j).getLiveAddress()) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                            map.put(key, value);
                        }
                    }
                    break;
                case "性别":
                    key = users.get(i).getSex();
                    if (key == null || key.equals("")) {
                        key = "未知";
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = 0; j < users.size(); j++) {
                            String strTemp = users.get(j).getSex();
                            if ((strTemp == null || strTemp.equals("")) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                            map.put(key, value);
                        }
                    } else {
                        value = map.get(key);
                        if (value == null) {
                            value = new ArrayList<>();
                        }
                        for (int j = i; j < users.size(); j++) {
                            if (key.equals(users.get(j).getSex()) && !value.contains(users.get(j))) {
                                value.add(users.get(j));
                            }
                        }
                        map.put(key, value);
                    }
                    break;
                default:
            }
        }
        Set<String> tempSet = map.keySet();
        TreeSet<String> keysSet = new TreeSet<>();
        keysSet.addAll(tempSet);
        Iterator<String> iterator = keysSet.iterator();
        int size = keysSet.size();
        generalsTypes = new String[size];
        generals = new ArrayList<>();
        int i = 0;
        //iterator
        while (iterator.hasNext()) {
            List<StudentUserLocal> list = new ArrayList<>();
            String key = iterator.next();//key
            generalsTypes[i] = key;
            List<StudentUserLocal> userList = map.get(key);//value
            for (int j = 0; j < userList.size(); j++) {
                list.add(userList.get(j));
            }
            i++;
            generals.add(list);
        }
    }
}
